package cn.listener;

import cn.TCSP;
import cn.util.TCUtil;
import cn.wetcland.dao.ConsumeRecordDao;
import cn.wetcland.dao.OrderRecordDao;
import cn.wetcland.dao.WetclandPlayerDao;
import cn.wetcland.pojo.ConsumeRecord;
import cn.wetcland.pojo.OrderRecord;
import cn.wetcland.pojo.WetclandPlayer;
import com.mcrmb.PayApi;
import com.mcrmb.event.McrmbPayEvent;
import com.mcrmb.event.QrDoneEvent;
import com.mcrmb.event.QrRequestEvent;
import org.apache.ibatis.session.SqlSession;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;

import java.sql.Timestamp;
import java.util.Date;

public class McrmbEventListener implements Listener {

    // todo 指令 b give 手动添加节操币， 更新数据库

    @EventHandler
    public void playerPayEvent(McrmbPayEvent event) {
        String response = event.getResponse() + "";
        System.out.println("-----发生玩家支付事件-----");
        System.out.println("玩家名 String" + event.getPlayer());
        System.out.println("消费点券 int" + event.getMoney());
        System.out.println("点券余额 int" + event.getLatestBalance());
        System.out.println("获取消费原因" + event.getReason());
        System.out.println("是否公屏" + event.isBroadcast());
        System.out.println("获取消费结果" + event.getResponse());
        Bukkit.getScheduler().runTaskAsynchronously(TCSP.getTcsp(), () -> {
            ConsumeRecord consumeRecord = new ConsumeRecord();
            consumeRecord.setPlayerName(event.getPlayer());
            consumeRecord.setConsume(event.getMoney());
            consumeRecord.setBalance(event.getLatestBalance());
            consumeRecord.setReason(event.getReason());
            consumeRecord.setBroadcast(event.isBroadcast() + "");
            consumeRecord.setResponse(event.getResponse() + "");
            consumeRecord.setDate(new Date());
            SqlSession sqlSession = TCSP.getSqlSessionFactory().openSession(true);
            ConsumeRecordDao mapper = sqlSession.getMapper(ConsumeRecordDao.class);
            mapper.addNewConsumeRecord(consumeRecord);
            sqlSession.close();
        });

    }

    // 二维码发起事件监听
    @EventHandler
    public void playerQrRequestEvent(QrRequestEvent qr) {
        System.out.println("----- 发生二维码请求事件 -----");
        System.out.println("玩家名：" + qr.getPlayer());
        System.out.println("充值金额：" + qr.getMoney());
        System.out.println("支付渠道：" + qr.getQd());
        System.out.println("二维码内容：" + qr.getQr());
        System.out.println("订单ID：" + qr.getId());
        System.out.println("提示信息：" + qr.getMsg());
        System.out.println("结果（SUCCESS=成功   ERROR=失败  NETWORK=接口问题）：" + qr.getResponse()); //SUCCESS = 成功   ERROR = 失败  NETWORK = 接口问题
    }

    // 2.0b17 新增
    // 扫码支付完成事件监听，注意，该事件仅在MCRMB插件内发起扫码充值后会产生。 如果你是自己调用MCRMB插件的发起二维码接口，将不会有支付完成事件。
    @EventHandler
    public void playerQrDoneEvent(QrDoneEvent qrdone) {
        String response = qrdone.getResponse() + "";
        System.out.println("----- 发生支付结果检查事件 -----");
        System.out.println("玩家名：" + qrdone.getPlayer());
        System.out.println("充值金额：" + qrdone.getMoney());
        System.out.println("充值点券：" + qrdone.getPoint());
        System.out.println("支付渠道：" + qrdone.getQd());
        System.out.println("订单ID：" + qrdone.getId());
        System.out.println("订单创建时间戳：" + qrdone.getCreate_time());
        System.out.println("订单完成时间戳：" + qrdone.getDone_time());
        System.out.println("结果（PAID=成功  UNPAID=未支付,轮询中 TIMEOUT=超过5分钟未支付）：" + qrdone.getResponse()); //PAID=成功  UNPAID=未支付 TIMEOUT=超过5分钟未支付
        if (response.equals("PAID")) {
            System.out.println("支付成功");
            // 异步处理
            Bukkit.getScheduler().runTaskAsynchronously(TCSP.getTcsp(), () -> {
                SqlSession sqlSession = TCSP.getSqlSessionFactory().openSession(true);
                WetclandPlayerDao mapper = sqlSession.getMapper(WetclandPlayerDao.class);
                OrderRecordDao orderRecordMapper = sqlSession.getMapper(OrderRecordDao.class);
                WetclandPlayer attrPlayer = TCUtil.getAttrPlayer(qrdone.getPlayer().getName());
                attrPlayer.setIntegrity(PayApi.look(qrdone.getPlayer().getName()));
                mapper.updatePlayer(attrPlayer);
                OrderRecord orderRecord = new OrderRecord();
                orderRecord.setOwnerId(attrPlayer.getId());
                orderRecord.setOrderId(qrdone.getId());
                orderRecord.setOwnerName(attrPlayer.getPlayerName());
                orderRecord.setPayType(qrdone.getQd());
                orderRecord.setCreateTime(new Timestamp(Long.parseLong(qrdone.getCreate_time()) * 1000));
                orderRecord.setDoneTime(new Timestamp(Long.parseLong(qrdone.getDone_time()) * 1000));
                orderRecord.setMoney(qrdone.getMoney());
                orderRecordMapper.addNewOrderRecord(orderRecord);
                sqlSession.close();
            });
            qrdone.getPlayer().sendTitle("§a支付成功", "", 10, 10, 10);
        } else if (response.equals("UNPAID")) {
            System.out.println("未支付");
            qrdone.getPlayer().sendTitle("§b未支付", "", 10, 10, 10);
        } else if (response.equals("TIMEOUT")) {
            System.out.println("支付超时");
            qrdone.getPlayer().sendTitle("§c支付超时", "", 10, 10, 10);
        }
    }

}
